package cn.yogehaoren.container;

import cn.yogehaoren.config.ServerConfig;
import cn.yogehaoren.handler.HttpManagerHandler;
import com.haojiangbo.constant.ConstantValue;
import com.haojiangbo.inteface.Container;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import lombok.extern.slf4j.Slf4j;


/**
 * @author WangNing yogehaoren@gamil.com <br>
 * @since 1.0
 */
@Slf4j
public class HttpManagerContainer  implements Container {

    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    ServerBootstrap serverBootstrap = new ServerBootstrap();

    @Override
    public void start() {
        serverBootstrap.group(workerGroup, bossGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new HttpServerCodec());
                        ch.pipeline().addLast(new HttpObjectAggregator(1024*1024));
                        ch.pipeline().addLast(new HttpManagerHandler());

                    }
                })
                .option(ChannelOption.SO_BACKLOG, ConstantValue.SO_BACKLOG_VALUE)
                .bind(ServerConfig.INSTANCE().getHttpPort()).addListener((ChannelFutureListener) future -> {
                    if(future.isSuccess()){
                        log.info("HTTP管理端口启动... 监听端口...{}",ServerConfig.INSTANCE().getHttpPort());
                    }else{
                        log.error("HTTP管理引擎启动失败...");
                    }
        });

    }

    @Override
    public void stop() {

        // 优雅关闭
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();

    }
}
